package dao.Client;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import model.Client;
import abstractFactory.Factory;

public class ClientDAOJPA implements ClientDAO{
	EntityManager manager;
	EntityManagerFactory fact;
	
	public EntityManager getManager() {
		if(manager == null) {
			manager = Factory.getFactory().createEntityManager();
		}
		return manager;
	}
	
	public boolean save(Client client){
		try	{
			getManager().getTransaction().begin();
			getManager().merge(client);
			getManager().getTransaction().commit();
			getManager().close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	public List<Client> listAll(){
		getManager().getTransaction().begin();
		Query query = (Query) getManager().createQuery("SELECT c FROM Client c where c.active = 1" );
		@SuppressWarnings("unchecked")
		List<Client> Clients =  query.getResultList();
		getManager().close();
		return Clients;
	}
	public List<Client> listAll(int inicio, int quant){
		getManager().getTransaction().begin();
		Query query = (Query) getManager().createQuery("SELECT c FROM Client c where c.active = 1" );
		@SuppressWarnings("unchecked")
		List<Client> clients =  query.setMaxResults(quant).setFirstResult(inicio).getResultList();
		getManager().close();
		return clients;
	}
	public Long totalClients(){
		getManager().getTransaction().begin();
		Query query = (Query) getManager().createQuery("SELECT count(c) FROM Client c where c.active = 1" );
		Long total = (Long) query.getSingleResult();
		getManager().close();
		return total;
	}
	public Client logClient(String name, String pass){
		try {
			getManager().getTransaction().begin();
			Query query = (Query) getManager().createQuery("SELECT c FROM Client c where c.login = :n and c.password = :p" );
			query.setParameter("n", name);
			query.setParameter("p", pass);
			Client client = (Client) query.getSingleResult();
			getManager().close();
			if(client != null)
				return client;
			else
				return null;
			} 
			catch (Exception e) {	
				return null;				
			}
	}
	public boolean update(Client client){
		try{
			getManager().getTransaction().begin();
			getManager().merge(client);
			getManager().getTransaction().commit();
			getManager().close();
			return true;
		}catch (Exception e) {
			return false;
		}
	}
	public boolean delete(Client client){

		try {
			getManager().getTransaction().begin();
			getManager().merge(client);
			getManager().getTransaction().commit();
			getManager().close();				
			return true;
		} catch (Exception e) {
			return false;
		}

	}
	public Client list(int id){

		try {
			getManager().getTransaction().begin();	
			Client client = getManager().find(Client.class, id);
			getManager().close();
			return client;
		} 
		catch (Exception e) {	
			return null;				
		}
	}
}
